package com.smh.yunpicturebackend.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smh.yunpicturebackend.exception.BusinessException;
import com.smh.yunpicturebackend.exception.ErrorCode;
import com.smh.yunpicturebackend.mapper.SpaceMapper;
import com.smh.yunpicturebackend.pojo.domain.Picture;
import com.smh.yunpicturebackend.pojo.domain.Space;
import com.smh.yunpicturebackend.pojo.domain.SpaceUser;
import com.smh.yunpicturebackend.pojo.domain.User;
import com.smh.yunpicturebackend.pojo.dto.space.SpaceAddRequest;
import com.smh.yunpicturebackend.pojo.dto.space.SpaceDeleteRequest;
import com.smh.yunpicturebackend.pojo.dto.space.SpaceQueryRequest;
import com.smh.yunpicturebackend.pojo.dto.spaceuser.SpaceUserAddRequest;
import com.smh.yunpicturebackend.pojo.enums.SpaceLevelEnum;
import com.smh.yunpicturebackend.pojo.enums.SpaceRoleEnum;
import com.smh.yunpicturebackend.pojo.enums.SpaceTypeEnum;
import com.smh.yunpicturebackend.pojo.vo.space.SpaceVO;
import com.smh.yunpicturebackend.pojo.vo.user.UserVO;
import com.smh.yunpicturebackend.service.PictureService;
import com.smh.yunpicturebackend.service.SpaceService;
import com.smh.yunpicturebackend.service.SpaceUserService;
import com.smh.yunpicturebackend.service.UserService;
import com.smh.yunpicturebackend.utils.ThrowUtils;
import com.smh.yunpicturebackend.utils.UserThreadLocal;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author shiminghui
 * @description 针对表【space(空间)】的数据库操作Service实现
 * @createDate 2025-06-23 21:35:07
 */
@Service
public class SpaceServiceImpl extends ServiceImpl<SpaceMapper, Space>
        implements SpaceService {

    private final Map<Long, Object> lockMap = new ConcurrentHashMap<>();
    @Resource
    private TransactionTemplate transactionTemplate;
    @Resource
    private UserService userService;
    @Resource
    @Lazy
    private PictureService pictureService;
    @Resource
    @Lazy
    private SpaceUserService spaceUserService;

    @Override
    public long addSpace(SpaceAddRequest spaceAddRequest) {
        User user = UserThreadLocal.get();
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_LOGIN_ERROR);
        // 1）填充参数默认值
        Space space = buildInsertSpace(spaceAddRequest, user);
        //2）校验参数
        validSpace(space, true);
        //3）校验权限，非管理员只能创建普通级别的空间
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(space.getSpaceLevel());
        if (!userService.isAdmin() && spaceLevelEnum != SpaceLevelEnum.COMMON) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限创建此级别空间");
        }
        //4）同一个账号只能创建一个私有空间
        Object lock = lockMap.computeIfAbsent(user.getId(), k -> new Object());
        synchronized (lock) {
            try {
                //5）操作数据库
                Long newSpaceId = transactionTemplate.execute(status -> {
                    if (!userService.isAdmin()) {
                        boolean isExist = this.lambdaQuery()
                                .eq(Space::getUserId, user.getId())
                                .eq(Space::getSpaceType, space.getSpaceType())
                                .exists();
                        ThrowUtils.throwIf(isExist, ErrorCode.SYSTEM_ERROR, "每个用户每类空间只能创建一个");
                    }
                    ThrowUtils.throwIf(!save(space), ErrorCode.SYSTEM_ERROR, "创建失败");
                    // 如果是团队空间,则将创建者插入空间用户表中
                    if (space.getSpaceType() == SpaceTypeEnum.TEAM.getValue()) {
                        SpaceUserAddRequest spaceUserAddRequest = new SpaceUserAddRequest();
                        spaceUserAddRequest.setSpaceId(space.getId());
                        spaceUserAddRequest.setUserId(user.getId());
                        spaceUserAddRequest.setSpaceRole(SpaceRoleEnum.ADMIN.getValue());
                        spaceUserService.addSpaceUser(spaceUserAddRequest);
                    }
                    return space.getId();
                });
                return Optional.ofNullable(newSpaceId).orElse(-1L);
            } finally {
                // 移除
                lockMap.remove(user.getId());
            }
        }
    }

    /**
     * 校验空间参数
     *
     * @param space space
     * @param add   是否为创建时检验
     */
    @Override
    public void validSpace(Space space, boolean add) {
        ThrowUtils.throwIf(space == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        String spaceName = space.getSpaceName();
        Integer spaceLevel = space.getSpaceLevel();
        Integer spaceType = space.getSpaceType();

        SpaceLevelEnum levelEnum = SpaceLevelEnum.getEnumByValue(spaceLevel);
        SpaceTypeEnum enumByValue = SpaceTypeEnum.getEnumByValue(spaceType);
        // 要创建
        if (add) {
            if (StringUtils.isBlank(spaceName)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间名称不能为空");
            }
            if (levelEnum == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间级别为空或不存在");
            }
            if (enumByValue == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间类型为空或不存在");
            }
        }
        if (StringUtils.isNotBlank(spaceName) && spaceName.length() > 30) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间名称过长");
        }
    }

    @Override
    public SpaceVO getSpaceVO(Space space) {
        // 对象转封装类
        SpaceVO spaceVO = SpaceVO.objToVo(space);
        // 关联查询用户信息
        Long userId = space.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            spaceVO.setUser(userVO);
        }
        return spaceVO;
    }

    @Override
    public Page<SpaceVO> getSpaceVOPage(Page<Space> spacePage) {
        List<Space> spaceList = spacePage.getRecords();
        Page<SpaceVO> spaceVOPage = new Page<>(spacePage.getCurrent(), spacePage.getSize(), spacePage.getTotal());
        if (CollUtil.isEmpty(spaceList)) {
            return spaceVOPage;
        }
        // 对象列表 => 封装对象列表
        List<SpaceVO> spaceVOList = spaceList.stream()
                .map(SpaceVO::objToVo)
                .collect(Collectors.toList());
        // 1. 关联查询用户信息
        // 1,2,3,4
        Set<Long> userIdSet = spaceList.stream().map(Space::getUserId).collect(Collectors.toSet());
        // 1 => user1, 2 => user2
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息
        spaceVOList.forEach(spaceVO -> {
            Long userId = spaceVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            spaceVO.setUser(userService.getUserVO(user));
        });
        spaceVOPage.setRecords(spaceVOList);
        return spaceVOPage;
    }

    @Override
    public QueryWrapper<Space> getQueryWrapper(SpaceQueryRequest spaceQueryRequest) {
        QueryWrapper<Space> queryWrapper = new QueryWrapper<>();
        if (spaceQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = spaceQueryRequest.getId();
        Long userId = spaceQueryRequest.getUserId();
        String spaceName = spaceQueryRequest.getSpaceName();
        Integer spaceLevel = spaceQueryRequest.getSpaceLevel();
        String sortField = spaceQueryRequest.getSortField();
        String sortOrder = spaceQueryRequest.getSortOrder();
        Integer spaceType = spaceQueryRequest.getSpaceType();


        // 拼接查询条件
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "user_id", userId);
        queryWrapper.like(StrUtil.isNotBlank(spaceName), "space_name", spaceName);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceLevel), "space_level", spaceLevel);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceType), "space_type", spaceType);
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }


    /**
     * 根据空间级别，自动填充限额
     *
     * @param space 空间
     */
    @Override
    public void fillSpaceBySpaceLevel(Space space) {
        // 根据空间级别，自动填充限额
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(space.getSpaceLevel());
        long maxSize = spaceLevelEnum.getMaxSize();
        if (space.getMaxSize() == null) {
            space.setMaxSize(maxSize);
        }
        long maxCount = spaceLevelEnum.getMaxCount();
        if (space.getMaxCount() == null) {
            space.setMaxCount(maxCount);
        }
    }

    /**
     * 删除空间
     *
     * @param spaceDeleteRequest 空间删除请求
     * @return 是否删除成功
     */
    @Override
    public boolean deleteSpace(SpaceDeleteRequest spaceDeleteRequest) {
        User user = UserThreadLocal.get();
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_LOGIN_ERROR);

        final Long spaceId = spaceDeleteRequest.getSpaceId();
        validDeleteSpace(spaceId, user);
        transactionTemplate.execute((status -> {
            // 删除空间
            ThrowUtils.throwIf(!removeById(spaceId), ErrorCode.OPERATION_ERROR, "删除失败");
            // 删除空间用户关系
            boolean remove = spaceUserService.remove(new LambdaQueryWrapper<SpaceUser>()
                    .eq(SpaceUser::getSpaceId, spaceId));
            ThrowUtils.throwIf(!remove, ErrorCode.OPERATION_ERROR, "删除空间用户关系失败");
            // 删除相关图片
            List<Picture> pictures = pictureService.lambdaQuery()
                    .eq(Picture::getSpaceId, spaceId)
                    .eq(Picture::getUserId, user.getId())
                    .list();

            if (!CollectionUtils.isEmpty(pictures)) {
                pictureService.removeByIds(pictures.stream().map(Picture::getId).collect(Collectors.toList()));
                pictureService.deletePictureFiles(pictures);
            }
            return null;
        }));
        return true;
    }

    @Override
    public boolean addPictureToSpace(long spaceId, Picture picture) {
        return this.lambdaUpdate()
                .eq(Space::getId, spaceId)
                .setSql("total_size = total_size + " + picture.getPicSize())
                .setSql("total_count = total_count + 1")
                .update();
    }

    @Override
    public boolean updatePictureToSpace(long spaceId, Picture picture, Picture oldPicture) {
        return this.lambdaUpdate()
                .eq(Space::getId, spaceId)
                .setSql("total_size = total_size - " + oldPicture.getPicSize() + " + " + picture.getPicSize())
                .update();
    }

    @Override
    public boolean deletePictureFromSpace(long spaceId, Picture picture) {
        return this.lambdaUpdate()
                .eq(Space::getId, spaceId)
                .setSql("total_size = total_size - " + picture.getPicSize())
                .setSql("total_count = total_count - 1")
                .update();
    }

    /**
     * 检查空间权限
     *
     * @param space 空间
     */
    @Override
    public void checkSpaceAuth(Space space) {
        User user = UserThreadLocal.get();
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_LOGIN_ERROR);
        ThrowUtils.throwIf(!space.getUserId().equals(user.getId()) && !userService.isAdmin(), ErrorCode.NO_AUTH_ERROR, "无操作权限");
    }

    /**
     * 删除空间
     *
     * @param spaceId
     * @param user
     */
    private void validDeleteSpace(Long spaceId, User user) {
        ThrowUtils.throwIf(spaceId == null, ErrorCode.PARAMS_ERROR);
        // 获取空间
        Space space = getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        ThrowUtils.throwIf(!space.getUserId().equals(user.getId()), ErrorCode.NO_AUTH_ERROR, "无操作权限");
    }


    /**
     * 构建插入空间
     *
     * @param spaceAddRequest
     * @param user
     * @return
     */
    private Space buildInsertSpace(SpaceAddRequest spaceAddRequest, User user) {
        // 默认值
        if (StrUtil.isBlank(spaceAddRequest.getSpaceName())) {
            spaceAddRequest.setSpaceName("默认空间");
        }
        if (spaceAddRequest.getSpaceLevel() == null) {
            spaceAddRequest.setSpaceLevel(SpaceLevelEnum.COMMON.getValue());
        }
        if (spaceAddRequest.getSpaceType() == null) {
            spaceAddRequest.setSpaceType(SpaceTypeEnum.PRIVATE.getValue());
        }

        Space space = new Space();
        BeanUtils.copyProperties(spaceAddRequest, space);
        space.setUserId(user.getId());
        // 根据空间级别，自动填充限额
        fillSpaceBySpaceLevel(space);
        return space;
    }
}






